<template>
  <div style="margin-left: 20px">
    <!--顶部功能-->
    <div style="margin-top: 20px">
      <el-input style="width: 330px" v-model="filterText" placeholder="请输入任务名进行搜索" clearable>
        <template #append>
          <el-button type="primary" @click="searchClick">查询</el-button>
        </template>
      </el-input>
      <el-button
        type="primary"
        style="float: right;margin-right: 20px"
        @click="popup('add')"
        icon="el-icon-plus"
          >新建任务
      </el-button>
    </div>
    <!--表格功能-->
    <el-scrollbar height="calc(100vh - 110px)">
      <div style="margin-top: 15px;margin-right: 20px">
        <el-table ref="table" highlight-current-row :data="taskList" style="width: 100%" size="mini" border empty-text="暂无数据">
              <el-table-column label="序号" align="center" width="60">
                <template #default="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="任务名称" prop="taskName" align="center" width="300">
                <template #default="scope">
                  <router-link class="no-underline" :to="`/maskMgrDetail/`" style="color: #409eff" @click="clickTaskManage(scope.row)">{{ scope.row.taskName }}</router-link>
                </template>
              </el-table-column>
              <el-table-column label="任务类型" prop="taskType" width="150" align="center">
                <template #default="scope">
                  <el-tag effect="dark" v-if="scope.row.taskType==='10'">{{ taskTypeMap[scope.row.taskType.toString()] || scope.row.taskType }}</el-tag>
                  <el-tag v-else type="success" effect="dark">{{ taskTypeMap[scope.row.taskType.toString()] || scope.row.taskType }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="运行模式" prop="runPattern" width="150" align="center"/>
              <el-table-column label="运行状态" prop="status" width="150" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.status === '1'" type="warning">{{ scope.row.status }}</el-tag>
                  <el-tag v-if="scope.row.status === '0'" type="success">{{ scope.row.status }}</el-tag>
                  <el-tag v-if="scope.row.status === '99'" type="danger">{{ scope.row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="创建人" prop="creator" align="center"  width="120"/>
              <el-table-column label="创建时间" align="center" width="160">
                <template #default="scope">
                  {{ $tools.rTime(scope.row.create_time) }}
                </template>
              </el-table-column>
              <el-table-column label="更新人" prop="modifier" align="center" width="120"/>
              <el-table-column label="更新时间" align="center" width="160">
                <template #default="scope">
                  <a v-if="scope.row.update_time">{{$tools.rTime(scope.row.update_time)}}</a>
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="desc" align="center" width="300" show-overflow-tooltip>
              </el-table-column>
              <el-table-column label="操作" width="370" align="center" fixed="right">
                <template #default="scope">
                  <el-button @click="runTask(scope.row.id)" size="mini" type="primary" icon="el-icon-s-promotion">运行</el-button>
                  <el-button @click="clickCopy(scope.row)" size="mini" type="primary" icon="el-icon-copy-document">复制</el-button>
                  <el-button @click="clickTaskManage(scope.row)" size="mini" type="warning" icon="el-icon-menu">任务管理</el-button>
                  <el-button @click="delTask(scope.row.id)" size="mini" type="danger" plain icon="el-icon-delete">删除</el-button>
                </template>
              </el-table-column>
      </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination  background layout="total, prev, pager, next, jumper"
                      @current-change="currentPages"
                      :default-page-size="100"
                      :total="pages.count"
                      :current-page="pages.current"
                     next-text="下一页" prev-text="上一页">
        </el-pagination>
      </div>
    </el-scrollbar>
  </div>
  <!--新增任务弹窗-->
  <el-dialog :title="dialogTitle" v-model="dialogVisible"  width="35%" custom-class="class_dialog" :required="true" style="text-align:left" :before-close="clearValidation">
		<el-form :model="form"  :rules="rulesPerf" ref="perfRef" label-width="90px" style="max-width: 550px">
      <el-form-item label="任务名称"  prop="taskName" >
        <el-input  v-model="form.taskName"  maxlength="50" placeholder="请输入任务名称"/>
      </el-form-item>
      <el-form-item prop="project" label="所属项目" >
        <el-input v-model="form.proName"  disabled />
      </el-form-item>
			<el-form-item label="任务描述" prop="desc">
        <el-input type="textarea" v-model="form.desc" placeholder="请输入备注"/>
      </el-form-item>
      <el-form-item label="任务类型" prop="taskType">
        <el-radio-group v-model="selectTaskType">
          <el-radio  label="10">
            普通任务
          </el-radio>
          <el-radio  label="20">
            定时任务
          </el-radio>
        </el-radio-group>
          <span v-if="form.taskType === '20'" style="color: #7a7a7a"><i class="el-icon-info" style="margin-left:20px;color: #a5b1ff"></i>定时任务下只允许创建一个场景！</span>
      </el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="clearValidation" >取消</el-button>
				<el-button type="primary" @click="addTask" >确定</el-button>
			</span>
		</template>
	</el-dialog>

</template>

<script>
import {mapMutations, mapState} from "vuex";
import {ElNotification} from "element-plus";
export default {
  data() {
    return {
      // 状态码映射
      taskTypeMap: {'10': '普通任务', '20': '定时任务'},
      filterText: '',
      taskList: [],
      pages: {
        count: 0,
        current: 1
      },
      addDlg: false,
      form: {
        taskName: '',
        desc: '',
        project: '',
        taskType: '10',
        creator : '',
        modifier : ''
      },
      dialogVisible: false,
      dialogTitle: '',
      rulesPerf: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
      }
    }
  },
  mounted() {

  },
  computed: {
    ...mapState({
      pro: state => state.pro
    }),
    username() {
			return window.sessionStorage.getItem('username');
		},
    selectTaskType: {
      get() {
        return this.form.taskType.toString();
      },
      set(value) {
        this.form.taskType = value;
      }
    },

  },
  methods: {
    ...mapMutations(['checkedTask']),

    async allTask(page,query) {
     const response = await this.$api.getPerformanceTask(this.pro.id,page,query)
     if (response.status ===200){
				this.taskList = response.data.result;
				this.pages.count = response.data.count;
				this.pages.current = response.data.current;
			}
    },

    currentPages(currentPage) {
      this.allTask(1);
      this.pages.current = currentPage
    },

    searchClick() {
      this.allTask(1,this.filterText)
    },

    clickTaskManage(data) {
      this.$router.push({ name: 'maskMgrDetail' });
      this.checkedTask(data)
    },

    popup(type) {
      this.dialogVisible = true;
      // 根据不同的对话框类型设置标题
      switch (type) {
        case 'add':
          this.dialogTitle = '新建任务';
          this.form.creator = this.username;
          this.form.project = this.pro.id;
          this.form.proName = this.pro.name;
          delete this.form.modifier;
          break;

        default:
          this.dialogTitle = '';
          break;
      }
    },

    clearValidation() {
      this.dialogVisible = false;
      this.$refs.perfRef.clearValidate(); // 清除验证信息
      this.form = {
        taskName: '',
        desc: '',
        project: '',
        taskType: '10',
        creator : '',
        modifier : ''
      }
    },

    async addTask() {
      this.$refs.perfRef.validate(async vaild => {
      if (!vaild) return;
      const params = this.form
      const response = await this.$api.createPerformanceTask(params);
      if (response.status === 201) {
        this.$message({
          type: 'success',
          message: '添加成功',
          duration: 1000
        });
        this.clearValidation();
        this.allTask(1)
      }
      })
    },

    delTask(id) {
    this.$confirm('此操作将永久删除该任务, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const response = await this.$api.delPerformanceTask(id)
        if(response.status ===204){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 刷新页面
          this.allTask(1);
        }
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
  },

    async clickCopy(data) {
      const params = data
      params.taskName = params.taskName + '_副本'
      const response = await this.$api.createPerformanceTask(params);
      if (response.status === 201) {
        this.$message({
          type: 'success',
          message: '复制成功',
          duration: 1000
        });
        this.allTask(1)
      }
    },

    runTask(id) {
      ElNotification({
        title: '即将开放',
        message: '即将开放',
        type: 'success',
        duration:1000
      });
    }

  },
  created() {
    this.allTask(1)
  }
}
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>